package com.guo.anim.fallingstar;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;

public class RoundBitmapUtil {
    /**
     * 将图片转换为圆形的Bitmap
     * @param inBitmap 转换前的原图
     * @param mInsideImageRadius 目标半径
     * @return
     */
    public static Bitmap createRoundBitmap(Bitmap inBitmap, int mInsideImageRadius){
        Bitmap tempBitmap;
        //判断是否需要进行缩放
        if(inBitmap.getWidth() == (2 * mInsideImageRadius) && inBitmap.getHeight() == inBitmap.getWidth()){
            tempBitmap = inBitmap;
        }else {
            tempBitmap = Bitmap.createScaledBitmap(inBitmap, 2*mInsideImageRadius, 2*mInsideImageRadius, false);
        }
        //创建待输出图片的画布
        Bitmap result = Bitmap.createBitmap(tempBitmap.getWidth(), tempBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        //设置画布透明
        canvas.drawColor(0x00FFFFFF);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        //绘制要裁剪的圆形
        canvas.drawCircle(tempBitmap.getWidth()/2, tempBitmap.getHeight()/2, mInsideImageRadius, paint);
        //设置相交模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        Rect rect = new Rect(0, 0, tempBitmap.getWidth(), tempBitmap.getHeight());
        canvas.drawBitmap(tempBitmap, rect, rect, paint);
        canvas.setBitmap(null);
        tempBitmap.recycle();
        return result;
    }
}
